﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using VDataAdapter.EventManagement;

namespace VDataAdapter.QueueManagement
{
    class TimeOutQueueChecker : EventQueueChecker
    {
        private int _timeOut;

        private DateTime _start;

        public TimeOutQueueChecker(IEventProviderQueue queue, int timeOut)
            : base(queue)
        {
            _timeOut = timeOut;
        }

        public override Event CheckingQueue(EventType type)
        {
            Event e = null;
            _start = DateTime.Now;

            while (!_stopCheckingQueue)
            {
                switch (type)
                {
                    case EventType.FirstTime: e = _queue.GetFirstTimeEvent();
                        break;
                    case EventType.Stock: e = _queue.GetTop3PricesEvent();
                        break;
                    case EventType.Transaction: e = _queue.GetTransactionsEvent();
                        break;
                    case EventType.PutThrough: e = _queue.GetPtTopPricesEvent();
                        break;
                    case EventType.PutThroughTransaction: e = _queue.GetPtTransactionsEvent();
                        break;
                    case EventType.MarketInfo: e = _queue.GetMarketInfosEvent();
                        break;

                }

                if (e == null)
                {
                    TimeSpan span = DateTime.Now - _start;
                    if (span.TotalSeconds > _timeOut)
                    {
                        return null; // stop checking after time out
                    }
                    Thread.Sleep(50);
                }
                else
                {
                    _start = DateTime.Now; // reset start so that will not time out so long
                    return e;
                }
            }
            return null;
            }
    }
}
